package tank01;

import java.awt.*;

/**
 * @Auther: xiaofei
 * @Date: 2021/7/1 - 07 - 01 - 13:55
 * @Description: tank01
 * @version: 1.0
 */
public class Bullet {
    private static final int SPEED = 10;
    private int x,y;
    private Dir dir;
    private TankFrame tf;

    //计算子弹的宽度和高度
    public static int WIDTH = ResouceMgr.bulletU.getWidth();
    public static int HEIGHT = ResouceMgr.bulletU.getHeight();

    Rectangle rect = new Rectangle();

    private boolean living = true;
    private Group group = Group.BAD;

    public Group getGroup(){
        return group;
    }

    public void setGroup(Group group) {
        this.group = group;
    }

    public Bullet() {
    }

    public Bullet(int x, int y, Dir dir, Group group,TankFrame tf) {
        this.x = x;
        this.y = y;
        this.dir = dir;
        this.tf = tf;
        this.group = group;

        rect.x = this.x;
        rect.y = this.y;
        rect.width = WIDTH;
        rect.height = HEIGHT;

        tf.bullets.add(this);
    }


    public void paint(Graphics g){
        if(!living){
            tf.bullets.remove(this);
        }

        switch (dir){
            //把子弹换成图片
            case LEFT:
                g.drawImage(ResouceMgr.bulletL,x,y,null);
                break;
            case UP:
                g.drawImage(ResouceMgr.bulletU,x,y,null);
                break;
            case RIGHT:
                g.drawImage(ResouceMgr.bulletR,x,y,null);
                break;
            case DOWN:
                g.drawImage(ResouceMgr.bulletD,x,y,null);
                break;
        }
        move();
    }

    private void move() {
        switch(dir){
            case LEFT:
                x -= SPEED;
                break;
            case RIGHT:
                x += SPEED;
                break;
            case UP:
                y -= SPEED;
                break;
            case DOWN:
                x -= SPEED;
                break;
        }

        //每次移动之后更新rect的值
        rect.x = this.x;
        rect.y = this.y;
        if(x<0 || y<0 || x>TankFrame.GAME_WIDTH || y>TankFrame.GAME_HEIGHT){
            living = false;
        }
    }

    public void collideWith(Tank tank){
//        if(this.group == tank.getGroup()) return;

        if(rect.intersects(tank.rect)){
            tank.die();
            this.die();
            //调整爆炸位置
            int eX = tank.getX() + Tank.WIDTH/2 - Explode.WIDTH/2;
            int eY = tank.getY() + Tank.HEIGHT/2 - Explode.HEIGHT/2;
            tf.explodes.add(new Explode(eX,eY,tf));
        }
    }

    private void die(){
        this.living = false;
    }
}
